package com.ityun.ogapp.utils

import android.app.usage.UsageStats
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.provider.Settings
import java.util.*

class UsageStatsHelper(private val context: Context) {
    // 获取UsageStatsManager实例
    private val usageStatsManager: UsageStatsManager? by lazy {
        context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager?
    }

    // 检查是否有应用使用统计权限
    fun hasPermission(): Boolean {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            return false
        }

        val currentTime = System.currentTimeMillis()
        // 查询最近1小时内的应用使用记录
        val statsList = usageStatsManager?.queryUsageStats(
            UsageStatsManager.INTERVAL_DAILY,
            currentTime - 1000 * 60 * 60,
            currentTime
        )

        return statsList != null && statsList.isNotEmpty()
    }

    // 跳转到权限设置页面
    fun requestPermission() {
        val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS).apply {
            data = Uri.parse("package:${context.packageName}")
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        context.startActivity(intent)
    }

    // 获取后台运行的应用信息列表
    fun getRunningApps(): List<AppInfo> {
        val appInfoList = mutableListOf<AppInfo>()
        if (!hasPermission()) {
            return appInfoList
        }

        val currentTime = System.currentTimeMillis()
        // 获取最近1小时内的应用使用统计
        val usageStatsList = usageStatsManager?.queryUsageStats(
            UsageStatsManager.INTERVAL_DAILY,
            currentTime - 1000 * 60 * 60 * 7 * 24,
            currentTime
        ) ?: return appInfoList

        // 去重处理（保留每个包名的最新记录）
        val uniquePackages = mutableMapOf<String, UsageStats>()
        usageStatsList.forEach { stats ->
            uniquePackages[stats.packageName] = stats
        }

        val packageManager = context.packageManager
        uniquePackages.values.forEach { stats ->
            try {
                // 获取应用信息
                val appInfo = packageManager.getApplicationInfo(stats.packageName, 0)
                // 获取应用名称
                val appName = packageManager.getApplicationLabel(appInfo).toString()
                // 获取应用图标
                val appIcon = packageManager.getApplicationIcon(appInfo)
                appInfoList.add(AppInfo(appName, appIcon, stats.packageName))
            } catch (e: PackageManager.NameNotFoundException) {
                // 忽略未找到的应用（可能是系统组件）
                e.printStackTrace()
            }
        }

        return appInfoList
    }

    // 应用信息数据类（Kotlin特性，自动生成getter/setter）
    data class AppInfo(
        val name: String,
        val icon: Drawable,
        val packageName: String
    )

}
